package com.ellecity06.cwhiskymall.timer

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ViewModel
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch

/**
 * @author ellecity06
 * @time 2024/10/24 10:22
 * @des
 */
/**
 *
 * @param onTick 每 [interval] 毫秒，滴答一下
 */
fun LifecycleOwner.tickFlow(
    interval: Long = 1000,
    onTick: () -> Unit,
): Job {
    return lifecycleScope.launch {
        repeatOnLifecycle(Lifecycle.State.STARTED) {
            flow {
                while (true) {
                    delay(interval)
                    emit(null)
                }
            }.collect {
                onTick.invoke()
            }
        }
    }
}
fun ViewModel.tickFlow(
    interval: Long = 1000,
    onTick: () -> Unit,
): Job {
    return viewModelScope.launch {
            flow {
                while (true) {
                    delay(interval)
                    emit(null)
                }
            }.collect {
                onTick.invoke()
            }
    }
}